/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ifgi.sitcom.campusmapperNDrawer.activities;

import java.io.InputStream;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.gamificationlibrary.model.Player;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.plus.PlusClient;
import com.google.android.gms.plus.model.people.Person;
import com.google.android.gms.plus.model.people.Person.Image;
import com.ifgi.sitcom.campusmapperNDrawer.R;
import com.ifgi.sitcom.campusmapperNDrawer.controllers.CampusMapperApplication;
import com.ifgi.sitcom.campusmapperNDrawer.controllers.PlayerController;
import com.ifgi.sitcom.campusmapperNDrawer.gamedata.PlayerAdapter;
import com.ifgi.sitcom.campusmapperNDrawer.gamedata.SerialBitmap;
import com.ifgi.sitcom.campusmapperNDrawer.io.RDFReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ToggleButton;

public class SignInActivity extends BaseActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
              
        if (savedInstanceState == null)
        {
       	  android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

       	// Replace whatever is in the fragment_container view with this fragment,
       	// and add the transaction to the back stack
       	ft.replace(R.id.content_mainactivity, new LoadFragment());
       	ft.addToBackStack(null);

       	// Commit the transaction
       	ft.commit();
       
        }
    }

    @Override
    public void onConnected(Bundle connectionHint) {
   
	   super.onConnected(connectionHint);
	   updateButtons(true /* isSignedIn */);
       Person currentP=getmPlusClient().getCurrentPerson();
       new DownloadImage().execute(currentP.getImage().getUrl(),currentP.getDisplayName(), currentP.getId());
    }

    @Override
    public void onDisconnected() {
        
      super.onDisconnected();
      updateButtons(false /* isSignedIn */);
        
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        super.onConnectionFailed(result);
        updateButtons(false /* isSignedIn */);
    }

    private void updateButtons(boolean isSignedIn) {
    	LoadFragment fragment=(LoadFragment) getSupportFragmentManager().getFragments().get(0);
        if (isSignedIn) {
        	fragment.mProgressButton.setVisibility(View.VISIBLE);
        	fragment.mSignInButton.setVisibility(View.INVISIBLE);
         
        } else {
            if (getmConnectionResult() == null) {
            	fragment.mProgressButton.setVisibility(View.VISIBLE);
            	fragment.mSignInButton.setVisibility(View.INVISIBLE);
            
            } else {
            	fragment.mSignInButton.setVisibility(View.VISIBLE);
            	fragment.mProgressButton.setVisibility(View.INVISIBLE);
             
            }

        }
    }
    
    
    private class DownloadImage extends AsyncTask<String, Void, SerialBitmap> {
    	  
    	private String cName;
		private Player player;
		private String ID;
    
    	  protected SerialBitmap doInBackground(String... urls) {
    		  
    	      String urldisplay = urls[0];
    	      urldisplay=urldisplay.substring(0, urldisplay.length()-2)+"100";
    	      
    	      Log.v("urldisplay",urldisplay);
    	      cName=urls[1];
    	      SerialBitmap mIcon11 = null;
    	      try {
    	        InputStream in = new java.net.URL(urldisplay).openStream();
    	        mIcon11 = new SerialBitmap(in);
    	      } catch (Exception e) {
    	          Log.e("Error", e.getMessage());
    	          e.printStackTrace();
    	      }
    	      
    	      RDFReader rdfReader=new RDFReader();
    	      ID=urls[2];
    	      player=rdfReader.getPlayer(ID);
    	      
    	      return mIcon11;
    	  }

    	  protected void onPostExecute(SerialBitmap result) 
    	  {
    		  if(player==null)
    		  {
    		  Log.v("entered", "entered");
    		  CampusMapperApplication.getInstance().setPlayer(PlayerController.getInstance().createPlayer(cName,result, ID));
    		  PlayerController.getInstance().writePlayerDB(CampusMapperApplication.getInstance().getPlayer());
    		  }
    		  else
    		  {
    		  Log.v("no entered", "no entered");
    		  ((PlayerAdapter) player).setPicture(result);
    		  CampusMapperApplication.getInstance().setPlayer(PlayerController.getInstance().createPlayer(player));  
    		  }
    		  Intent intent = new Intent(SignInActivity.this,MainActivity.class);
      		  startActivity(intent);
      		  finish(); 
    	  }
    	}
    

	       	
    
	    public static class LoadFragment extends Fragment
	    {
	    private ProgressBar mProgressButton;
		private SignInButton mSignInButton;

		public LoadFragment() {}
	    
		    @Override
		    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
		    {
		    View rootView = inflater.inflate(R.layout.fragment1, container, false);
		    mSignInButton = (SignInButton) rootView.findViewById(R.id.sign_in_button);
		    setmProgressButton((ProgressBar) rootView.findViewById(R.id.progressBar1));
		    mSignInButton.setOnClickListener((OnClickListener) getActivity());
	      
		    return rootView;
		    }
	
			public ProgressBar getmProgressButton() {
				return mProgressButton;
			}
			
			public SignInButton getmSignInButton() {
				return mSignInButton;
			}
	
			public void setmProgressButton(ProgressBar mProgressButton) {
				this.mProgressButton = mProgressButton;
			}
	    }
	 
}
